import QtQuick 2.15
import QtQuick.Window 2.15
import QtQuick.Controls 2.15
import QtQuick.Layouts 1.15
import QtQuick.Controls.Material 2.15

ApplicationWindow {
    id: window
    width: 480
    height: 800
    visible: true
    title: "备忘录"
    
    // 主题色
    readonly property color primaryColor: "#6366f1"
    readonly property color backgroundColor: "#f8fafc"
    readonly property color cardColor: "#ffffff"
    readonly property color textColor: "#1e293b"
    readonly property color textSecondaryColor: "#64748b"
    
    Material.theme: Material.Light
    Material.accent: primaryColor
    
    // 备忘录列表模型
    ListModel {
        id: memoListModel
    }
    
    // 加载数据
    function loadMemos() {
        memoListModel.clear()
        var memos = memoStorage.loadMemos()
        for (var i = 0; i < memos.length; i++) {
            var memo = memos[i]
            memoListModel.append({
                memoId: memo.id,
                title: memo.title,
                content: memo.content,
                createdAt: memo.createdAt,
                updatedAt: memo.updatedAt
            })
        }
    }
    
    function formatDateTime(dateTimeStr) {
        if (!dateTimeStr) return ""
        var date = new Date(dateTimeStr)
        var year = date.getFullYear()
        var month = String(date.getMonth() + 1).padStart(2, '0')
        var day = String(date.getDate()).padStart(2, '0')
        var hours = String(date.getHours()).padStart(2, '0')
        var minutes = String(date.getMinutes()).padStart(2, '0')
        return year + "-" + month + "-" + day + " " + hours + ":" + minutes
    }
    
    // 初始化
    Component.onCompleted: {
        loadMemos()
    }
    
    // 背景
    Rectangle {
        anchors.fill: parent
        color: backgroundColor
    }
    
    // 页面堆栈
    StackView {
        id: stackView
        anchors.fill: parent
        initialItem: listPage
        
        // 列表页面
        Component {
            id: listPage
            
            Rectangle {
                color: backgroundColor
                
                ColumnLayout {
                    anchors.fill: parent
                    spacing: 0
                    
                    // 标题栏
                    Rectangle {
                        Layout.fillWidth: true
                        height: 70
                        color: primaryColor
                        
                        RowLayout {
                            anchors.fill: parent
                            anchors.leftMargin: 20
                            anchors.rightMargin: 20
                            
                            Text {
                                text: "📝 备忘录"
                                font.pixelSize: 36
                                font.bold: true
                                color: "white"
                                Layout.fillWidth: true
                            }
                            
                            // 添加按钮
                            Button {
                                text: "➕"
                                font.pixelSize: 32
                                flat: true
                                Material.foreground: "white"
                                width: 50
                                height: 50
                                onClicked: {
                                    var page = editPage.createObject(stackView, {
                                        memoId: -1,
                                        memoTitle: "",
                                        memoContent: ""
                                    })
                                    stackView.push(page)
                                }
                            }
                        }
                    }
                    
                    // 备忘录列表
                    ScrollView {
                        Layout.fillWidth: true
                        Layout.fillHeight: true
                        clip: true
                        
                        ListView {
                            id: memoListView
                            model: memoListModel
                            spacing: 1
                            
                            delegate: Rectangle {
                                id: memoCard
                                width: memoListView.width
                                height: 120
                                color: cardColor
                                
                                // 点击效果
                                Rectangle {
                                    anchors.fill: parent
                                    color: "#f0f0f0"
                                    opacity: mouseArea.pressed ? 0.3 : 0
                                    Behavior on opacity {
                                        NumberAnimation { duration: 100 }
                                    }
                                }
                                
                                property int memoId: model.memoId
                                property string memoTitle: model.title
                                property string memoContent: model.content
                                property string memoUpdatedAt: formatDateTime(model.updatedAt)
                                
                                // 点击进入编辑页
                                MouseArea {
                                    id: mouseArea
                                    anchors.fill: parent
                                    onClicked: {
                                        var page = editPage.createObject(stackView, {
                                            memoId: memoCard.memoId,
                                            memoTitle: memoCard.memoTitle,
                                            memoContent: memoCard.memoContent
                                        })
                                        stackView.push(page)
                                    }
                                }
                                
                                RowLayout {
                                    anchors.fill: parent
                                    anchors.leftMargin: 20
                                    anchors.rightMargin: 20
                                    spacing: 16
                                    
                                    ColumnLayout {
                                        Layout.fillWidth: true
                                        spacing: 8
                                        
                                        Text {
                                            text: memoTitle || "无标题"
                                            font.pixelSize: 28
                                            font.bold: true
                                            color: textColor
                                            elide: Text.ElideRight
                                            Layout.fillWidth: true
                                        }
                                        
                                        Text {
                                            text: memoContent || "无内容"
                                            font.pixelSize: 22
                                            color: textSecondaryColor
                                            elide: Text.ElideRight
                                            maximumLineCount: 2
                                            Layout.fillWidth: true
                                        }
                                        
                                        Text {
                                            text: memoUpdatedAt
                                            font.pixelSize: 18
                                            color: textSecondaryColor
                                            Layout.fillWidth: true
                                        }
                                    }
                                    
                                    // 删除按钮
                                    Button {
                                        text: "🗑️"
                                        flat: true
                                        Material.foreground: "#ef4444"
                                        font.pixelSize: 28
                                        width: 50
                                        height: 50
                                        onClicked: {
                                            deleteConfirmDialog.memoId = memoCard.memoId
                                            deleteConfirmDialog.memoTitle = memoCard.memoTitle
                                            deleteConfirmDialog.open()
                                        }
                                    }
                                }
                                
                                // 分割线
                                Rectangle {
                                    anchors.bottom: parent.bottom
                                    anchors.left: parent.left
                                    anchors.right: parent.right
                                    height: 1
                                    color: "#e2e8f0"
                                }
                            }
                            
                            // 空状态提示
                            Label {
                                anchors.centerIn: parent
                                visible: memoListModel.count === 0
                                text: "还没有备忘录\n点击右上角➕按钮创建第一条"
                                font.pixelSize: 24
                                color: textSecondaryColor
                                horizontalAlignment: Text.AlignHCenter
                            }
                        }
                    }
                }
            }
        }
        
        // 编辑页面
        Component {
            id: editPage
            
            Rectangle {
                id: editPageRoot
                color: backgroundColor
                
                property int memoId: -1
                property string memoTitle: ""
                property string memoContent: ""
                
                // 初始化数据
                Component.onCompleted: {
                    titleField.text = memoTitle || ""
                    contentArea.text = memoContent || ""
                }
                
                ColumnLayout {
                    anchors.fill: parent
                    spacing: 0
                    
                    // 标题栏
                    Rectangle {
                        Layout.fillWidth: true
                        height: 70
                        color: primaryColor
                        
                        RowLayout {
                            anchors.fill: parent
                            anchors.leftMargin: 20
                            anchors.rightMargin: 20
                            
                            // 返回按钮
                            Button {
                                text: "←"
                                font.pixelSize: 32
                                flat: true
                                Material.foreground: "white"
                                width: 50
                                height: 50
                                onClicked: {
                                    stackView.pop()
                                }
                            }
                            
                            Text {
                                text: editPageRoot.memoId === -1 ? "新建备忘录" : "编辑备忘录"
                                font.pixelSize: 28
                                font.bold: true
                                color: "white"
                                Layout.fillWidth: true
                            }
                            
                            // 保存按钮
                            Button {
                                text: "保存"
                                font.pixelSize: 22
                                flat: true
                                Material.foreground: "white"
                                width: 60
                                height: 50
                                onClicked: {
                                    if (titleField.text.trim() === "") {
                                        errorToast.show("标题不能为空")
                                        return
                                    }
                                    
                                    var id = editPageRoot.memoId === -1 ? memoStorage.getNextId() : editPageRoot.memoId
                                    if (memoStorage.saveMemo(id, titleField.text, contentArea.text)) {
                                        loadMemos()
                                        stackView.pop()
                                    } else {
                                        errorToast.show("保存失败")
                                    }
                                }
                            }
                        }
                    }
                    
                    // 编辑区域 - 全屏布局
                    ColumnLayout {
                        Layout.fillWidth: true
                        Layout.fillHeight: true
                        spacing: 0
                        
                        // 标题输入区域
                        Rectangle {
                            Layout.fillWidth: true
                            Layout.preferredHeight: 100
                            color: cardColor
                            
                            TextField {
                                id: titleField
                                anchors.fill: parent
                                anchors.leftMargin: 20
                                anchors.rightMargin: 20
                                anchors.topMargin: 20
                                anchors.bottomMargin: 20
                                placeholderText: "标题"
                                font.pixelSize: 32
                                Material.accent: primaryColor
                            }
                        }
                        
                        // 分割线
                        Rectangle {
                            Layout.fillWidth: true
                            height: 2
                            color: "#e2e8f0"
                        }
                        
                        // 内容输入区域 - 全屏可编辑
                        ScrollView {
                            Layout.fillWidth: true
                            Layout.fillHeight: true
                            clip: true
                            
                            TextArea {
                                id: contentArea
                                width: parent.width
                                placeholderText: "内容..."
                                font.pixelSize: 26
                                wrapMode: TextArea.Wrap
                                Material.accent: primaryColor
                                padding: 20
                            }
                        }
                    }
                }
            }
        }
    }
    
    // 删除确认对话框
    Dialog {
        id: deleteConfirmDialog
        property int memoId: -1
        property string memoTitle: ""
        
        x: (parent ? parent.width : 480) / 2 - width / 2
        y: (parent ? parent.height : 800) / 2 - height / 2
        width: (parent ? parent.width : 480) - 64
        height: 200
        modal: true
        
        ColumnLayout {
            anchors.fill: parent
            spacing: 16
            anchors.margins: 16
            
            Text {
                Layout.fillWidth: true
                text: "确认删除"
                font.pixelSize: 28
                font.bold: true
                color: textColor
            }
            
            Text {
                Layout.fillWidth: true
                text: "确定要删除「" + deleteConfirmDialog.memoTitle + "」吗？\n此操作不可恢复。"
                font.pixelSize: 20
                color: textSecondaryColor
                wrapMode: Text.Wrap
            }
            
            RowLayout {
                Layout.fillWidth: true
                
                Button {
                    Layout.fillWidth: true
                    text: "取消"
                    Material.background: "#e2e8f0"
                    Material.foreground: textColor
                    onClicked: deleteConfirmDialog.close()
                }
                
                Button {
                    Layout.fillWidth: true
                    text: "删除"
                    Material.background: "#ef4444"
                    Material.foreground: "white"
                    onClicked: {
                        if (memoStorage.deleteMemo(deleteConfirmDialog.memoId)) {
                            loadMemos()
                            deleteConfirmDialog.close()
                        } else {
                            errorToast.show("删除失败")
                        }
                    }
                }
            }
        }
    }
    
    // 错误提示Toast
    Rectangle {
        id: errorToast
        anchors.horizontalCenter: parent.horizontalCenter
        anchors.bottom: parent.bottom
        anchors.bottomMargin: 50
        width: parent.width - 32
        height: 60
        radius: 8
        color: "#ef4444"
        visible: false
        z: 1000
        
        function show(message) {
            errorToastText.text = message
            errorToast.visible = true
            errorToastTimer.start()
        }
        
        Text {
            id: errorToastText
            anchors.centerIn: parent
            color: "white"
            font.pixelSize: 18
            width: parent.width - 32
            wrapMode: Text.Wrap
            horizontalAlignment: Text.AlignHCenter
        }
        
        Timer {
            id: errorToastTimer
            interval: 3000
            onTriggered: errorToast.visible = false
        }
    }
}
